import { get, isEmpty, groupBy, nth, capitalize } from 'lodash'
import { v4 } from 'uuid'

export function getCharge (prices, periodUnit = 'month', mode) {
  const charges = prices || []
  const plan = charges.find(i => i.type === 'plan' && i.periodUnit === periodUnit && i.status === 'active') || {}
  const addon = charges.find(i => i.type === 'addon' && i.periodUnit === periodUnit && i.status === 'active' && i.itemId !== 'Attendance-Dashboard-User-addon') || {}
  const str = mode === 3 ? 'per User per Bot' : 'per User'
  let charge = {
    unit: capitalize(periodUnit) || periodUnit
  }

  if ((addon.pricingModel === 'flat_fee' || addon.pricingModel === 'per_unit')) {
    charge.addon = [get(addon, 'price', 0) / 100 || 0, str, addon]
    charge.addonOtherId = addon.otherId
  }
  if (addon.pricingModel === 'tiered') {
    charge.tiers = get(addon, 'tiers', []).sort((a, b) => a.price - b.price).map(i => ({ ...i, price: i.price / 100 || 0 }))
    charge.addonOtherId = addon.otherId
  }

  if (!isEmpty(plan)) {
    charge.plan = [get(plan, 'price', 0) / 100 || 0, periodUnit, plan]
    charge.planOtherId = plan.otherId
  }

  return charge
}

export function getGroupCharges (prices) {
  const group = groupBy(prices || [], 'periodUnit')
  return [{ type: 'month', value: group.month || [] }, { type: 'year', value: group.year || [] }]
}

export function getTotalMRR (charge = {}, {
  seats = 1,
  bots = 1
}) {
  let total = 0
  let units = seats * bots
  const { addon, tiers, plan } = charge

  if (plan && plan.length) {
    total += plan[0]
  }
  if (addon && addon.length && (addon[2].pricingModel === 'per_unit' || addon[2].pricingModel === 'flat_fee')) {
    total += addon[0] * units
  }
  if (tiers && tiers.length) {
    total += tiers.reduce((result, record) => {
      const { price, starting_unit: startingUnit, ending_unit: endingUnit } = record
      if (units >= startingUnit && units <= (endingUnit || Infinity)) {
        result += (units - startingUnit + 1) * price
      }
      if (endingUnit && units >= endingUnit) {
        result += endingUnit * price
      }
      return result
    }, 0)
  }
  return total
}

export function getDisplayCharge (prices, type, userLimit) {
  const charges = prices || []
  const plan = charges.find(i => i.type === 'plan' && i.status === 'active') || {}
  const addon = charges.find(i => i.type === 'addon' && i.status === 'active') || {}
  const str = userLimit === 3 ? 'per User per Bot' : 'per User'
  let charge = [0]
  if (type === 'plan' && !isEmpty(plan)) {
    charge = [plan.price / 100 || 0]
    return charge
  }
  if (addon.pricingModel === 'tiered') {
    charge.tiers = get(addon, 'tiers', []).sort((a, b) => a.price - b.price).map(i => ({ ...i, price: i.price / 100 || 0 }))
    const last = nth(charge.tiers, -1)
    if (last.price) {
      charge = [last.price, str]
    }
  } else if (addon.pricingModel === 'flat_fee' || addon.pricingModel === 'per_unit') {
    charge = [addon.price / 100 || 0, str]
  } else if (!isEmpty(plan)) {
    charge = [plan.price / 100 || 0]
  }

  return charge
}

export function getBundleStatus (index, bundles) {
  const second = bundles[1]
  const third = bundles[2]
  const four = bundles[3] || null
  if (four && four.subscriptionStatus && index < 3) {
    return 'low'
  }

  if (index === 0) {
    if (!second.subscriptionStatus && !third.subscriptionStatus) {
      return 'current'
    }
    if (second.subscriptionStatus || third.subscriptionStatus) {
      return 'low'
    }
  }
  if (index === 1) {
    if (second.subscriptionStatus && !third.subscriptionStatus) {
      return 'current'
    }
    if (third.subscriptionStatus) {
      return 'low'
    }
    if (!second.subscriptionStatus && !third.subscriptionStatus) {
      return 'upgrade'
    }
  }
  if (index === 2) {
    if (!third.subscriptionStatus) {
      return 'upgrade'
    }
    if (third.subscriptionStatus) {
      return 'current'
    }
  }
  if (index === 3 && four) {
    if (!four.subscriptionStatus) {
      return 'upgrade'
    }
    if (four.subscriptionStatus) {
      return 'current'
    }
  }
}

export function getMarketRule (instance) {
  const { seats, bots, product, code } = instance
  const appId = get(product, 'appId')
  const rule = {
    appId
  }
  let threshold = {}

  if (product.userLimit === 1) {
    rule.type = '11'
    // const value = Number(get(subscription, 'threshold.value') || 0)
    threshold.resourceId = appId
    threshold.value = String(seats)
  }
  if (product.userLimit === 2) {
    rule.type = '13'
    threshold.value = code
  }
  if (product.userLimit === 3) {
    rule.type = '12'
    // const value = Number(get(subscription, 'threshold.value') || 0)
    threshold.value = String(bots)
  }
  if (product.userLimit === 4) {
    rule.type = '12'
    threshold.value = 'Infinity'
  }

  rule.threshold = threshold
  threshold.extra = {
    seats, bots, code, appId
  }

  return rule
}

export function getAppUsers (free, pay, appId) {
  const freeUsers = (free || []).map(i => ({
    accountType: 1,
    userId: i.id,
    appId
  }))
  const payUsers = (pay || []).map(i => ({
    accountType: 2,
    userId: i.id,
    appId
  }))
  return [...freeUsers, ...payUsers]
}

export function isPayBundle (bundles) {
  return bundles.some(i => i.subscriptionStatus)
}

export function isPayBIAndBot (bis, bots) {
  return [...bis, ...bots].some(i => i.subscriptionStatus)
}

export function getResourceType (resourceType) {
  if (resourceType === 1) {
    return 0
  }
  if (resourceType === 5) {
    return 1
  }
  if (resourceType === 4) {
    return 3
  }
}

export function getSnapshots (resource) {
  const origin = 'https://appint.mspbots.ai'
  let url
  if (resource.resourceType === 1) {
    url = `dashboard-${resource.resourceId}?pageid=${resource.resourceId}&name=${resource.resourceName}`
  }
  if (resource.resourceType === 5) {
    url = `dataset-${resource.resourceId}?pageid=${resource.resourceId}&name=${resource.resourceName}`
  }
  if (resource.resourceType === 4) {

  }

  return `${origin}/${url}&shareToken=${v4()}`
}

export function getExtraUsers (instance) {
  const { selectdPayUser, bots = 1, product, whiteList } = instance
  const paySeats = selectdPayUser.filter(account => !isWhite(whiteList, account))
  if (product.userLimit === 0) {
    return paySeats.length > 10 ? paySeats.length : 10
  }
  if (product.userLimit === 1) {
    return paySeats.length
  }
  if (product.userLimit === 3) {
    return paySeats.length * bots
  }
  if (product.userLimit === 4) {
    return paySeats.length
  }
}

export function getUrl (path = '', query = {}) {
  let [url, search] = path.split('?')
  const searchParams = new URLSearchParams(search)
  searchParams.forEach((val, key) => {
    query[key] = val
  })

  return {
    path: url,
    query
  }
}

export function isWhite (whites = [], account = {}) {
  return whites.some(white => {
    if (white.type === 0) {
      return white.freeAccount === account.username && white.status === 1
    }
    if (white.type === 1) {
      let roleIds = []
      if (white.roleIds) {
        roleIds = white.roleIds.split(',')
      }
      return account.roleIds.some(id => roleIds.includes(id)) && white.tenantName === account.tenantName && white.status === 1
    }
    if (white.type === 2) {
      return (account.username || '').indexOf(white.tenantName) !== -1 && white.status === 1
    }

    return false
  })
}
